const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    part: false, // 仅小组可看 开启/关闭 控制标识
    all: false, // 全部可看 开启/关闭 控制标识
    self: false, // 仅自己可看 开启/关闭 控制标识
    experience_review_src: [ // 提交心得评分五角星icon图标列表
      "../../static/images/index/star.jpg",
      "../../static/images/index/star.jpg",
      "../../static/images/index/star.jpg",
      "../../static/images/index/star.jpg",
      "../../static/images/index/star.jpg"
    ],
    article_review_src: [ // 阅读文章评分五角星icon图标列表
      "../../static/images/index/star.jpg",
      "../../static/images/index/star.jpg",
      "../../static/images/index/star.jpg",
      "../../static/images/index/star.jpg",
      "../../static/images/index/star.jpg"
    ],
    // experience_score: 0, // 提交心得评分
    // read_score: 0, // 阅读文章评分
    data: {}, // 用户心得数据
    repair: [], // 心得内容存放列表
    content_json: [], // 心得类型列表
    work_id: '', // 作业ID
    classId: '',
    company_id: '',
    personal_read_id: '',
    study_id: '', // 用户提交作业ID，用来控制当前页面是显示用户的心得内容还是让用户填写心得（''：未完成，value：已完成）
    // status: false, // 修改功能是否显示
    study_comment: [], // 评论列表
    selectCommentIndex: '', // 长按评论选中的评论下标
    is_draft: '', // 作业是暂存/完成状态（1：暂存，2：完成）
    showInput: false, // 是否弹出评论框
    commentContent: '', // 评论内容
    touchStartTime: '', // 开始触摸组件时的时间戳（用来模拟长按）
    isLongTap: false, // 是否触发长按事件
    fontSetSize: 'small', // 用户设置的字体大小（'small'：小，'middle'：中，'large'：大）
    article_id:"" ,
    credit:0 ,
    creditNum:0
  },

  // 提交心得评分
  /*ReviewChange(e) {
    let index = e.currentTarget.dataset.idx
    let list = this.data.experience_review_src;
    for (let i = 0; i < 5; i++) {
      if (index <= i) {
        list[i] = "../../static/images/index/star_select.jpg";
      } else {
        list[i] = "../../static/images/index/star.jpg";
      }
    }
    let experience_score = 5 - index
    this.setData({
      experience_score,
      experience_review_src: list
    })
  },*/

  // 阅读文章评分
  /*ArticleChange(e) {
    let index = e.currentTarget.dataset.idx
    let list = this.data.article_review_src;
    for (let i = 0; i < 5; i++) {
      if (index <= i) {
        list[i] = "../../static/images/index/star_select.jpg";
      } else {
        list[i] = "../../static/images/index/star.jpg";
      }
    }
    let read_score = 5 - index
    this.setData({
      read_score,
      article_review_src: list
    })
  },*/

  // 仅小组可看
  onChangePart(event) {
    let detail = event.detail
    if (this.data.part) {
      this.setData({
        part: detail.value
      })
    } else {
      let all = !detail.value
      let self = !detail.value
      this.setData({
        part: detail.value,
        all,
        self
      })
    }
    console.log(detail.value, this.data.part)
  },

  // 全部可看
  onChangeAll(event) {
    let detail = event.detail
    if (this.data.all) {
      this.setData({
        all: detail.value
      })
    } else {
      let part = !detail.value
      let self = !detail.value
      this.setData({
        all: detail.value,
        part,
        self
      })
    }
    console.log(detail.value, this.data.all)
  },

  // 仅自己可看
  onChangeSelf(event) {
    let detail = event.detail
    if (this.data.self) {
      this.setData({
        self: detail.value
      })
    } else {
      let part = !detail.value
      let all = !detail.value
      this.setData({
        self: detail.value,
        part,
        all
      })
    }
    console.log(detail.value, this.data.self)
  },

  // 复制
  copy(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.text,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功'
            })
          }
        })
      }
    })
  },

  // 复制文本
  copyText: function (e) {
    this.copy(e);
  },

  // 输入内容
  handleInputChange (e) {
    let idx = e.currentTarget.dataset.idx
    let val = e.detail.value
    let repair = this.data.repair
    repair[idx] = val
    this.setData({
      repair
    })
  },

  /**
   * 作业暂存(本地缓存，该方案已废弃，改为后端存储)
   */
  /*handleTemporaryStorage () {
    let temporaryStorage = [] // 第一次缓存作业内容时用来存放作业内容
    let tempObj = {} // 用来存放当前作业内容
    // 当前作业内容
    tempObj.work_id = this.data.work_id
    tempObj.content_json = this.data.content_json
    tempObj.repair = this.data.repair
    // tempObj.experience_score = this.data.experience_score
    // tempObj.read_score = this.data.read_score
    tempObj.part = this.data.part
    tempObj.all = this.data.all
    tempObj.self = this.data.self
    temporaryStorage.push(tempObj)
    // 获取本地缓存的作业内容列表
    let lastTemporaryStorage = wx.getStorageSync('temporaryStorage')
    // 本地缓存的作业内容列表存在，进行下一步判断
    if (lastTemporaryStorage.length) {
      let len = lastTemporaryStorage.length
      for (let i = 0; i < len; i++) {
        // 通过work_id值来判断本地缓存中是否存在当前作业上次存放的作业内容，如果存在，先删除本地缓存中上次存放的作业内容，再将最新的作业内容存放到本地缓存
        if (lastTemporaryStorage[i].work_id == this.data.work_id) {
          lastTemporaryStorage.splice(i, 1)
          lastTemporaryStorage.push(tempObj)
          wx.setStorageSync('temporaryStorage', lastTemporaryStorage)
        }
      }
    } else {
      // 本地缓存中没有作业内容列表，执行第一次作业内容缓存
      wx.setStorageSync('temporaryStorage', temporaryStorage)
    }
    wx.showToast({
      icon: 'success',
      title: '暂存成功'
    })
  },*/
  
  /**
   * 判断心得内容是否有emoji表情
   * @param {心得内容} substring 
   */
  isEmojiCharacter(substring) {
    for ( let i = 0; i < substring.length; i++) {
      let hs = substring.charCodeAt(i);
      if (0xd800 <= hs && hs <= 0xdbff) {
        if (substring.length > 1) {
          let ls = substring.charCodeAt(i + 1);
          let uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
          if (0x1d000 <= uc && uc <= 0x1f77f) {
            return true;
          }
        }
      } else if (substring.length > 1) {
        let ls = substring.charCodeAt(i + 1);
        if (ls == 0x20e3) {
          return true;
        }
      } else {
        if (0x2100 <= hs && hs <= 0x27ff) {
          return true;
        } else if (0x2B05 <= hs && hs <= 0x2b07) {
          return true;
        } else if (0x2934 <= hs && hs <= 0x2935) {
          return true;
        } else if (0x3297 <= hs && hs <= 0x3299) {
          return true;
        } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
          return true;
        }
      }
    }
  },

  /**
   * 暂存/提交心得
   */
  handleSubmit (e) {
    let is_draft = e.currentTarget.dataset.is_draft
    let token = wx.getStorageSync('token')
    let study_json_content = []
    let content_json = this.data.content_json
    let repair = this.data.repair
    let len = this.data.content_json.length
    let balnk = false
    let isEmojiCharacter = false
    let article_id = this.data.article_id;
    console.log(repair)
    for (let i = 0; i < len; i++) {
      if (repair[i] == '') {
        balnk = true
      } else {
        let work_obj = {}
        work_obj.k = content_json[i]
        work_obj.v = repair[i]
        if (!isEmojiCharacter) {
          isEmojiCharacter = this.isEmojiCharacter(repair[i])
        }
        study_json_content.push(work_obj)
      }
    }
    study_json_content = JSON.stringify(study_json_content)
    if (balnk) {
      wx.showToast({
        title: '心得内容不能有空白',
        icon: 'none',
      })
      let timer = setTimeout(() => {
        wx.hideToast()
        clearTimeout(timer)
      }, 1500)
      return false
    }
    if (isEmojiCharacter) {
      wx.showToast({
        title: '心得内容不能包含表情',
        icon: 'none',
      })
      let timer = setTimeout(() => {
        wx.hideToast()
        clearTimeout(timer)
      }, 1500)
      return false
    }
    let is_opend = ''
    if (this.data.part) {
      is_opend = 1
    } else if (this.data.all) {
      is_opend = 2
    } else if (this.data.self) {
      is_opend = 3
    } else {
      wx.showToast({
        title: '请选择公开权限',
        icon: 'none',
      })
      let timer = setTimeout(() => {
        wx.hideToast()
        clearTimeout(timer)
      }, 1500)
      return false
    }
   

    app.http({
      config: {
        url: '/api/User/add_work',
        data: {
          token,
          class_work_id: this.data.work_id,
          is_opend,
          study_json_content,
          is_draft ,
          article_id
        },
        method: 'POST'
      },
      isAuth: true
    }).then(res => {
      
      console.log(res, 'workJsonRes')
      wx.showToast({
        icon: 'success',
        title: res.data.message
      })
    
      if(res.data.data.integral_day >= 1){
        this.setData({
           credit:true ,
           creditNum:res.data.data.integral_day
        })
      }else{
        let timer = setTimeout(() => {
          wx.navigateBack({
            delta: 2,
          })
          clearTimeout(timer)
        }, 3000)
      }
    }).catch(err => {
      console.log(err, 'workJsonErr')
      wx.showModal({
        title: '提示：',
        content: err.data.message,
        showCancel: false,
      })
    })
  },

  // 获取用户的作业详情（已完成作业再回到该页面的时候）
  getUserExperience () {
    let token = wx.getStorageSync('token')
    let study_id = this.data.study_id
    app.http({
      config: {
        url: '/api/User/my_study_info',
        data: {
          token,
          study_id
        },
        method: 'POST'
      },
      isAuth: true
    }).then(res => {
      console.log(res, 'userExperienceRes')
      let data = res.data.data
      let is_draft = res.data.data.is_draft
      let study_json_content = data.study_json_content
      this.setData({
        is_draft,
        data
      })
      switch (data.is_opend) { // is_opend 心得公开情况（1：仅小组可看，2：全部可看，3：仅自己可看）
        case '1':
          this.setData({
            part: true,
            all: false,
            self: false
          })
          break;
        case '2':
          this.setData({
            part: false,
            all: true,
            self: false
          })
          break;
        case '3':
          this.setData({
            part: false,
            all: false,
            self: true
          })
          break;
        default:
          console.log(data.is_opend, 'default')
      }
      if (study_json_content) { // JSON格式心得作业存在
        let content_json = []
        let repair = []
        study_json_content.forEach(item => {
          content_json.push(item.k)
          repair.push(item.v)
        })
        this.setData({
          content_json,
          repair
        })
        if (is_draft == '2') {
          let experience_review_src = []
          // for循环，改变"提交心得"五角星图标为点亮状态
          for (let i = 0; i < 5; i++) {
            experience_review_src[i] = "../../static/images/index/star_select.jpg"
          }
          let study_comment = data.study_commnet // 评论列表
          this.setData({
            experience_review_src,
            study_comment
          })
        }
      }
    }).catch(err => {
      console.log(err, 'userExperienceErr')  
    })
  },

  // 修改提交的作业
  handleChangeExperience (e) {
    let is_draft = e.currentTarget.dataset.is_draft
    let token = wx.getStorageSync('token')
    let is_opend = ''
    if (this.data.part) {
      is_opend = 1
    } else if (this.data.all) {
      is_opend = 2
    } else if (this.data.self) {
      is_opend = 3
    }
    let study_json_content = []
    let content_json = this.data.content_json
    let repair = this.data.repair
    let len = this.data.content_json.length
    for (let i = 0; i < len; i++) {
      let work_obj = {}
      work_obj.k = content_json[i]
      work_obj.v = repair[i]
      study_json_content.push(work_obj)
    }
    study_json_content = JSON.stringify(study_json_content)
    app.http({
      config: {
        url: '/api/User/edit_work',
        data: {
          token,
          study_id: this.data.study_id,
          is_opend,
          study_json_content,
          is_draft
        },
        method: 'POST'
      },
      isAuth: true
    }).then(res => {
      console.log(res, 'changeWorkJsonRes')
      wx.showToast({
        icon: 'success',
        title: res.data.message
      })
      let timer = setTimeout(() => {
        wx.hideToast()
        wx.navigateBack({
          delta: 2,
        })
        clearTimeout(timer)
      }, 1500)
    }).catch(err => {
      console.log(err, 'changeWorkJsonErr')
      wx.showModal({
        title: '提示：',
        content: err.data.message,
        showCancel: false,
      })
    })
  },

  // 点击评论按钮，拉起输入框
  handleComment () {
    this.setData({
      showInput: true
    })
  },

  // 提交评论内容
  formSubmit (e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
    let comment = e.detail.value.comment
    let study_id = this.data.study_id
    let token = wx.getStorageSync('token')
    app.http({
      config: {
        url: '/api/User/create_study_comment',
        data: {
          token,
          study_id,
          comment
        },
        method: 'POST'
      },
      isAuth: true
    }).then(res => {
      console.log(res, 'commentRes')
      this.getUserExperience()
      this.pageScrollToBottom()
    }).catch(err => {
      console.log(err, 'commentErr')
    })
  },

  // 长按选中评论，弹出删除评论按钮
  handleSelectComment (e) {
    let selectCommentIndex = e.currentTarget.dataset.idx
    this.setData({
      selectCommentIndex
    })
  },

  // 点击页面任意地方取消评论选中状态
  handleDeleteSelectComment () {
    this.setData({
      selectCommentIndex: ''
    })
  },

  // 删除评论
  deleteComment (e) {
    let study_comment_id = e.currentTarget.dataset.comment
    let token = wx.getStorageSync('token')
    app.http({
      config: {
        url: '/api/User/del_study_comment',
        data: {
          token,
          study_comment_id
        },
        method: 'POST'
      },
      isAuth: true
    }).then(res => {
      console.log(res, 'deleteCommentRes')
      this.setData({
        selectCommentIndex: ''
      })
      this.getUserExperience()
    }).catch(err => {
      console.log(err, 'deleteCommentErr')
    })
  },

  // 评论输入框失去焦点
  inputBlur () {
    this.setData({
      showInput: false
    })
  },

  // 评论输入框获得焦点
  inputFous () {
    this.setData({
      commentContent: ''
    })
    this.pageScrollToBottom()
  },

  //页面自动滚动到底部
  pageScrollToBottom: function () {
    wx.createSelectorQuery().select('.intro').boundingClientRect(function(rect){
      // console.log(rect);
      wx.pageScrollTo({
        scrollTop: rect.height,
      })
    }).exec()
  },

  /**
   * 点赞
   * @param {学习ID} e 
   */
  handleSupport (e) {
    let study_id = e.currentTarget.dataset.study_id
    let token = wx.getStorageSync('token')
    app.http({
      config: {
        url: '/api/User/create_support',
        data: {
          token,
          study_id
        },
        method: 'POST'
      },
      isAuth: true
    }).then(res => {
      console.log(res, 'supportRes')
      this.getUserExperience()
    }).catch(err => {
      console.log(err, 'supportErr')
    })
  },

  /**
   * 取消点赞
   * @param {学习ID} e 
   */
  handleDeleteSupport (e) {
    let study_id = e.currentTarget.dataset.study_id
    let token = wx.getStorageSync('token')
    app.http({
      config: {
        url: '/api/User/del_support',
        data: {
          token,
          study_id
        },
        method: 'POST'
      },
      isAuth: true
    }).then(res => {
      console.log(res, 'DeleteSupportRes')
      this.getUserExperience()
    }).catch(err => {
      console.log(err, 'DeleteSupportErr')
    })
  },

  // 分享
  onShare () {
    this.onShareAppMessage()
  },

  onLoad: function (options) {
    let _this = this
    let study_id = options.study_id // 用户提交的作业ID，判断用户是否已经暂存/提交了作业
    let work_id = options.work_id
    let classId = options.classId
    let company_id = options.company_id
    let personal_read_id = options.personal_read_id
    let article_id = options.articleId
    _this.setData({
      work_id,
      study_id,
      classId,
      company_id,
      personal_read_id,
      article_id
    })

    if (study_id) { // 用户已经暂存/提交了作业
      this.getUserExperience() // 获取用户的作业详情
    } else {
      // let content_json = options.content_json.split(",")
      // let len = content_json.length
      // let repair = []
      // for (let i = 0; i < len; i++) {
      //   repair.push('')
      // }
      // _this.setData({
      //   repair,
      //   content_json
      // })
    }
  },

  /*onLoad: function (options) {
    let _this = this
    let study_id = options.study_id // 用户提交的作业ID，判断用户是否已经完成了作业
    this.setData({
      study_id
    })
    if (study_id) { // 用户完成作业
      this.getUserExperience() // 获取用户的作业详情
    } else { // 用户未完成作业，查询本地缓存中是否存在该作业的缓存（即：用户是不是之前有进入这个页面写作业并点击了暂存，只是还没提交）
      let work_id = options.work_id
      let temporaryStorage = wx.getStorageSync('temporaryStorage')
      // 本地缓存中存在作业内容列表
      if (temporaryStorage) {
        let len = temporaryStorage.length
        // 遍历本地缓存中的作业内容列表
        for (let i = 0; i < len; i++) {
          // 通过对比work_id来找到当前作业在本地缓存中的作业内容，并将内容更新到data中
          if (temporaryStorage[i].work_id == work_id) {
            let experience_review_src = _this.data.experience_review_src
            let article_review_src = _this.data.article_review_src
            for (let k = 0; k < temporaryStorage[i].experience_score; k++) {
              let idx = 4 - k
              experience_review_src[idx] = "../../static/images/index/star_select.jpg"
            }
            for (let j = 0; j < temporaryStorage[i].read_score; j++) {
              let idx = 4 - j
              article_review_src[idx] = "../../static/images/index/star_select.jpg"
            }
            _this.setData({
              work_id: temporaryStorage[i].work_id,
              content_json: temporaryStorage[i].content_json,
              repair: temporaryStorage[i].repair,
              // experience_score: temporaryStorage[i].experience_score,
              // read_score: temporaryStorage[i].read_score,
              part: temporaryStorage[i].part,
              all: temporaryStorage[i].all,
              self: temporaryStorage[i].self,
              // experience_review_src,
              // article_review_src
            })
          }
        }
      } else { // 本地缓存中不存在作业内容列表
        let content_json = options.content_json.split(",")
        let len = content_json.length
        let repair = []
        for (let i = 0; i < len; i++) {
          repair.push('')
        }
        _this.setData({
          work_id,
          repair,
          content_json
        })
      }
    }
    console.log(options)
  },*/

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let fontSetSize = wx.getStorageSync('fontSetSize') // 本地缓存中用户设置的字体大小
    if (fontSetSize) {
      this.setData({
        fontSetSize
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面转发按钮
      console.log(res.target, res)
    }
    if (this.data.classId) {
      return {
        title: '心得详情',
        path: 'pages/index_sixitem_signup/index_sixitem_signup?id=' + this.data.classId 
      }
    } else if (this.data.company_id) {
      return {
        title: '心得详情',
        path: 'pages/index_company_signup/index_company_signup?id=' + this.data.company_id
      }
    } else if (this.data.personal_read_id) {
      return {
        title: '心得详情',
        path: 'pages/index_student_signup/index_student_signup?personal_read_id=' + this.data.personal_read_id
      }
    }
  }
})